<?php
namespace Cli\Controller;
class ArticleController extends CommonController {
    /**
     * 定期更新文章
     *
     * @param     void
     * @return    void
     **/
    public function publish() {
        $Category = D('Category','Mysql');

        $Article = D('Article','Mysql');

        $ArticleMongo = D('Article','Mongo');

        $length = 100;
        $offset = 0;

        $publish_num_per_category = 10;
        while(true) {
            $categoryList = $Category->where("`status` = 1 and `auto_publish` = 1")->limit($offset.','.$length)->select();
            if(!$categoryList) break;

            $time = time();

            foreach($categoryList as $value) {
                $cid = $value['id'];
                $articleInfo = $Article->where("`cid` = {$cid}")->field('publishtime')->order("publishtime desc")->find();

                if($articleInfo['publishtime'] > $time + 86400 * 7) {
                    continue;               
                }

                $articleList = $ArticleMongo->where(array('cid.' . $cid =>intval($cid)))->order('hotnum desc')->limit("0,10")->select();
                if(!$articleList) continue;

                $publishtime = $articleInfo['publishtime'] < $time ? $time : $articleInfo['publishtime'];

                foreach($articleList as $article) {
                    $publishtime += (86400 / 10) + rand(5000,10000);
                    try{
                        $result = $Article->review(array(
                            'mongoid' =>    $article['id'],
                            'title'     =>  $article['title'],
                            'content'   =>  str_replace('data-src','src',$article['content']),
                            'author'    =>  $article['author'],
                            'sid'       =>  $value['sid'],
                            'cid'       =>  $cid,
                            'source_name'   =>  $article['source_name'],
                            'source_url'    =>  $article['source_url'],
                            'hotnum'        =>  $article['hotnum'],
                            'tags'          =>  arrayToString($article['tags'],20),
                            'publishtime'   =>  date('Y-m-d H:i:s',$publishtime),
                            'cover'         =>  $article['cover'],
                        ));
                    }catch(\Exception $e) {
                        echo $e->getMessage() . "\n";
                        // 日志记录
                    }
                }
            }

            $offset += $length;
        }
    }
}
?>
